const Router = require("koa-router");

const { TokenValidator, NotEmptyValidator } = require("../../validators/token");

const { Auth } = require("@middlewares/auth");
const { WXManager } = require("../../services/wx");
const { redis } = require("@core/redis");
const router = new Router({
  prefix: "/v1/token",
});

// 获取 token
router.post("/", async (ctx) => {
  const v = await new TokenValidator().validate(ctx);

  // 登录方式：email || 小程序
  // API 权限 公开API
  // token 过期 不合法

  // 小程序登录
  // let token = await redis.get(`token:${v.get("body.account")}`);

  let token = await WXManager.codeToToken(v.get("body.account"), ctx);

  ctx.body = {
    code: 200,
    msg: "获取成功",
    data: {
      token: token,
    },
  };
});

// 验证token
router.post("/verify", async (ctx) => {
  const v = await new NotEmptyValidator().validate(ctx);
  const result = Auth.verifyToken(v.get("body.token"));

  ctx.body = {
    msg: "验证成功",
    code: 200,
    data: {
      isValid: result,
    },
  };
});

module.exports = router;
